<template>
  <div class="home-container">
    <!-- 使用Vant的NavBar作为顶部导航 -->
    <van-nav-bar title="热门内容" fixed placeholder />

    <!-- 使用Vant的Tabs组件作为分类标签 -->
    <van-tabs v-model:active="currentCategory" @change="handleCategoryChange" sticky>
      <van-tab v-for="category in categoriesList" :key="category.id" :title="category.name" :name="category.id"></van-tab>
    </van-tabs>

    <!-- 内容列表 -->
    <div class="content-section">
      <!-- 加载状态 -->
      <van-loading v-if="loading.contents" class="loading" size="24px" vertical>加载中...</van-loading>

      <!-- 错误状态 -->
      <van-empty v-else-if="error.contents" class="error" description="获取内容失败，请重试">
        <van-button round type="primary" @click="fetchContents(currentCategory)">重试</van-button>
      </van-empty>

      <!-- 内容列表 -->
      <div v-else class="content-list">
        <div v-for="content in contents" :key="content.content_id" class="content-card-wrapper">
          <van-card
              class="content-card"
              @click="handleContentClick(content.content_id)"
          >
            <!-- 自定义卡片内容 -->
            <template #header>
              <div class="card-header">
                <h3 class="content-title">{{ content.title || '无标题' }}</h3>
                <div class="content-meta">
                  <van-tag plain type="primary">{{ getTypeName(content.type) || '未知' }}</van-tag>
                  <van-tag plain type="success">{{ content.content_type === 2 ? '视频' : '帖子' }}</van-tag>
                </div>
              </div>
            </template>

            <template #thumb>
              <div class="media-container">
                <van-image
                    width="100"
                    height="80"
                    fit="cover"
                    :src="`https://picsum.photos/400/200?random=${content.content_id}`"
                    alt="内容配图"
                >
                  <template v-slot:error>加载失败</template>
                </van-image>

                <!-- 视频标识 -->
                <div v-if="content.content_type === 2" class="video-badge">
                  <van-icon name="play" size="16" color="#fff" />
                </div>
              </div>
            </template>

            <template #desc>
              <!-- 显示标题而非描述，保留原样式结构 -->
              <p class="content-title-display">{{ content.title || '无标题' }}</p>
            </template>

            <template #tags>
              <div class="content-stats">
                <span class="view-count">
                  <van-icon name="eye" size="14" /> {{ content.view_count || 0 }}
                </span>
                <span class="hot-value">
                  <van-icon name="fire" size="14" /> {{ content.hot || 0 }}
                </span>
              </div>
            </template>

            <template #footer>
              <div class="card-footer">
                <van-button
                    class="like-btn"
                    size="small"
                    @click.stop="handleLike(content.content_id)"
                    :icon="content.liked ? 'like' : 'like-o'"
                    :color="content.liked ? '#ee0a24' : ''"
                >
                  {{ content.like_count || 0 }}
                </van-button>
              </div>
            </template>
          </van-card>
        </div>
      </div>
    </div>

    <!-- 没有更多内容 -->
    <div v-if="!loading.contents && contents.length === 0" class="no-content">
      <van-empty description="暂无内容" />
    </div>

    <div v-else-if="!loading.contents && contents.length > 0" class="no-more">
      <van-divider>已经到底啦~</van-divider>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {
  NavBar,
  Tabs,
  Tab,
  Card,
  Button,
  Tag,
  Image as VanImage,
  Icon,
  Loading,
  Empty,
  Divider,
  Toast
} from 'vant';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

// 配置axios
axios.defaults.baseURL = '/api';
axios.interceptors.request.use(config => {
  config.withCredentials = true;
  return config;
});

// 数据存储 - 使用与后端对应的字段名
const contents = ref([]);
const loading = ref({ contents: false });
const error = ref({ contents: '' });
const currentCategory = ref('all');

// 类型映射
const typeMap = {
  'sports': '体育',
  'entertainment': '娱乐',
  'tech': '科技',
  'lifestyle': '生活'
};

const categoriesList = ref([
  { id: 'all', name: '推荐' },
  { id: 'sports', name: '体育' },
  { id: 'entertainment', name: '娱乐' },
  { id: 'tech', name: '科技' },
  { id: 'lifestyle', name: '生活' },
]);

// 切换分类的方法
const handleCategoryChange = async (categoryId) => {
  currentCategory.value = categoryId;
  await fetchContents(categoryId);
};

// 获取类型中文名称
const getTypeName = (type) => {
  return typeMap[type] || type;
};

// 从后端获取内容数据
const fetchContents = async (category = 'all') => {
  try {
    loading.value.contents = true;
    error.value.contents = '';

    let response;
    if (category === 'all') {
      response = await axios.get('/content/allContent');
    } else {
      response = await axios.get(`/content/getByType?type=${category}`);
    }

    if (response.data.code === 200) {
      // 确保字段名与后端一致
      const rawData = response.data.data || [];

      // 处理数据，初始化点赞状态
      contents.value = rawData.map(item => ({
        content_id: item.content_id,
        title: item.title,
        content_type: item.content_type,
        type: item.type,
        hot: item.hot,
        view_count: item.viewCount,
        like_count: item.likeCount,
        favorite_count: item.favoriteCount,
        comment_count: item.commentCount,
        created_at: item.createdAt,
        updated_at: item.updatedAt,
        url: item.url,
        details: item.details,
        user_id: item.userId,
        liked: false
      }));

      //按热度从高到低排序（仅针对 "推荐" 分类）
      if (category === 'all') {
        contents.value.sort((a, b) => b.hot - a.hot);
      }
    } else {
      error.value.contents = response.data.message || '获取内容失败';
      Toast.fail(error.value.contents);
    }
  } catch (err) {
    error.value.contents = '网络错误，无法连接到服务器';
    console.error('内容数据获取失败:', err);
    Toast.fail(error.value.contents);
  } finally {
    loading.value.contents = false;
  }
};

// 点击内容增加热度和浏览量
const handleContentClick = async (content_id) => {
  try {
    // 调用view接口增加热度
    await axios.post("/content/view", null, {params: {content_id}});

    // 更新本地数据
    const contentIndex = contents.value.findIndex(c => c.content_id === content_id);
    if (contentIndex !== -1) {
      // 创建新对象触发响应式更新
      contents.value[contentIndex] = {
        ...contents.value[contentIndex],
        view_count: (contents.value[contentIndex].view_count) + 1,
        hot: (contents.value[contentIndex].hot) + 1
      };
    }

    // 跳转到详情页
    goToDetails(content_id);
  } catch (err) {
    console.error('内容浏览量更新失败:', err);
    Toast.fail('操作失败，请重试');
  }
};

const goToDetails = (content_id) => {
  router.push(`/contentDetail/${content_id}`);
};

// 点赞/取消点赞功能
const handleLike = async (content_id) => {
  try {
    const contentIndex = contents.value.findIndex(c => c.content_id === content_id);
    if (contentIndex === -1) {
      Toast.fail('未找到对应内容');
      return;
    }

    const currentContent = contents.value[contentIndex];
    // 调用点赞/取消点赞接口（需要后端配合实现取消逻辑）
    await axios.post(currentContent.liked ? "/content/cancelLike" : "/content/like",
        null, {params: {content_id}});

    // 更新本地数据
    const changeValue = currentContent.liked ? -1 : 1;
    contents.value[contentIndex] = {
      ...currentContent,
      like_count: Math.max(0, (currentContent.like_count || 0) + changeValue),
      hot: Math.max(0, (currentContent.hot || 0) + (changeValue * 2)),
      liked: !currentContent.liked
    };

    Toast.success(currentContent.liked ? '取消点赞成功' : '点赞成功');
  } catch (err) {
    console.error('点赞操作失败:', err);
    Toast.fail('操作失败，请重试');
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchContents();
});
</script>

<style scoped>
.home-container {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.content-section {
  padding: 12px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.error {
  text-align: center;
  padding: 40px 20px;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.content-card-wrapper {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.content-card {
  border-radius: 8px;
}

.card-header {
  padding-bottom: 8px;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  color: #323233;
}

/* 标题展示样式 */
.content-title-display {
  font-size: 14px;
  color: #646566;
  margin-top: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.content-meta {
  display: flex;
  gap: 6px;
}

.media-container {
  position: relative;
  width: 100px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
}

.video-badge {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-stats {
  display: flex;
  gap: 12px;
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
}

.view-count, .hot-value {
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.like-btn {
  margin-left: auto;
}

.no-content, .no-more {
  color: #969799;
  font-size: 14px;
  padding: 20px 0;
  text-align: center;
}

:deep(.van-card__header) {
  padding-bottom: 0;
}

:deep(.van-card__content) {
  min-height: auto;
}

:deep(.van-tab) {
  font-size: 14px;
}

:deep(.van-tabs__line) {
  background-color: #07c160;
}
</style>